package com.spring.boot.test.config;

import com.alibaba.fastjson2.JSON;
import com.spring.boot.test.config.stragegy.CommonShardingAlgorithm;
import com.spring.boot.test.config.stragegy.ShardStragegyTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Desc: 分表策略
 */
@Slf4j
public class TableShardingAlgorithm extends CommonShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> {


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<String> shardingValue) {
        log.info("Table ComplexKeysShardingAlgorithm tableNames:{} ,ComplexKeysShardingValue: {}.", JSON.toJSONString(availableTargetNames),
                JSON.toJSONString(shardingValue));
        Map<String, Collection<String>> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Set<String> tableNameSet = new HashSet<>();

        //获取分表策略
        for (String key : columnNameAndShardingValuesMap.keySet()) {
            Collection<String> fieldValues = columnNameAndShardingValuesMap.get(key);
            if(!CollectionUtils.isEmpty(fieldValues)){
                fieldValues.stream().forEach(fieldValue -> {
                    if(StringUtils.isNotBlank(fieldValue)) {
                        for (String tableName : availableTargetNames) {
                            String suffix = super.getFieldShardStrategy(key, fieldValue, ShardStragegyTypeEnum.TABLE);
                            if (tableName.endsWith("_" + suffix)) {
                                log.info("shardingValue的fieldName:{},fieldValue:{}，选择到的表是：{},", key, fieldValue, tableName);
                                tableNameSet.add(tableName);
                                break;
                            }
                        }
                    }
                });
            }
        }
        if(!tableNameSet.isEmpty()){
            return tableNameSet;
        }
        throw new UnsupportedShardingOperationException("table error query param",shardingValue.getLogicTableName());
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}

